from machine import Pin, I2C
import utime

class mb_24x256_512:
    """Driver for Microchip 24x256/512 EEPROM devices"""

    def __init__(self, i2c, i2c_address, EEPROM_device):
        # Init with the I2C setting
        self.i2c = i2c
        self.i2c_address = i2c_address[0]

        if(EEPROM_device == "24x256"):
            self._MAX_ADDRESS = 32767
        elif(EEPROM_device == "24x512"):
            self._MAX_ADDRESS = 65535
        else:
            raise ValueError("Please choose a device from the list")

            return()

    # Done init, ready to go

    def write_byte(self, address, data):
        if((address > self._MAX_ADDRESS) or (address < 0)):
            raise ValueError("Address is outside of device address range")
            return()

        if((data > 255) or (data < 0)):
            raise ValueError("You can only pass an 8-bit data value 0-255 to this function")
            return()

        self.i2c.writeto_mem(self.i2c_address, address, bytes([data]), addrsize=16)
        utime.sleep_ms(10) # EEPROM needs time to write and will not respond if not ready


    def read_byte(self, address):
        if((address > self._MAX_ADDRESS) or (address < 0)):
            raise ValueError("Address is outside of device address range")
            return()

        self.value_read = bytearray(1)
        self.value_read = self.i2c.readfrom_mem(self.i2c_address, address, 1, addrsize=16)
        self.value_read = int.from_bytes(self.value_read, "big")
        return(self.value_read)